package com.jrapider.manager.data.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jrapider.manager.data.om.SysUser;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public interface SysUserMapper extends BaseMapper<SysUser> {

    @Update("update sys_user set password = #{password} where id=#{id} and password is null")
    long initPassword(@Param("id") Long id, @Param("password") String password);

    @Select(" SELECT " +
            "    t1.*" +
            " FROM" +
            "    sys_user t1" +
            "        INNER JOIN" +
            "    sys_user_role t2 ON t1.id = t2.user_id" +
            " WHERE" +
            "    t2.role_id = #{roleId}" +
            "    AND t1.login_id like #{loginId}")
    List<SysUser> queryUserWithRole(IPage<SysUser> page, @Param("loginId") String loginId, @Param("roleId") Long roleId);

    @Select(" SELECT " +
            "    t.*" +
            " FROM" +
            "    sys_user t" +
            " WHERE" +
            "    t.id NOT IN (SELECT " +
            "            t1.id" +
            "        FROM" +
            "            sys_user t1" +
            "                LEFT JOIN" +
            "            sys_user_role t2 ON t1.id = t2.user_id" +
            "        WHERE" +
            "            t2.role_id = #{roleId})" +
            "        AND t.login_id like #{loginId}")
    List<SysUser> queryUserWithNoRole(IPage<SysUser> page, @Param("loginId") String loginId, @Param("roleId") Long roleId);

    @Insert("<script>" +
            " insert into sys_user_role(user_id,role_id) " +
            " values " +
            " <foreach item='userId' index='index' collection='userIds' separator=','>" +
            "    (#{userId},#{roleId})" +
            " </foreach>" +
            "</script>")
    void insertUserRelation(@Param("roleId") Long roleId, @Param("userIds") Long[] userIds);

    @Delete("delete from sys_user_role where role_id = #{roleId} and user_id=#{userId}")
    void deleteUserRelation(@Param("roleId") Long roleId, @Param("userId") Long userId);


    @Select("select count(1) from sys_user_role where user_id = #{userId} and role_id = #{roleId}")
    Long existRole(@Param("userId") Long userId, @Param("roleId") Long roleId);

    @Select("select * from sys_user where login_id =#{loginId} and password=#{encode}")
    SysUser validate(@Param("loginId") String loginId, @Param("encode") String encode);

    @Update("update sys_user set password=#{newpwd} where login_id=#{loginId} and password=#{oldpwd}")
    int changePwd(@Param("loginId") String loginId, @Param("oldpwd") String oldpwd, @Param("newpwd") String newpwd);
}
